package com.wwt.server.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 获取验证码
 */
@Api(tags = "图片验证码")
@Controller
@Slf4j
@RestController
public class KaptchaController {
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @GetMapping("/kaptcha")
    @ApiOperation(value = "获取图片验证码",produces = "image/jpeg") //指定输出格式
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        //设置过期时间
        response.setDateHeader("Expires",0);
        //设置不缓存 HTTP1.1 IE扩展的1.1  1.0三种标准
        response.setHeader("Cache-Control", "no-store, no-cache, mustrevalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        //设置格式
        response.setContentType("image/jpeg");
        //获取文本验证码
        String text = defaultKaptcha.createText();
        log.info("############文本验证码：{}",text);
        //把验证码放入session中
        request.getSession().setAttribute("kaptcha",text);
        //生成图片
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream=null;
        try{
             outputStream = response.getOutputStream();
             //输出流输出图片
            ImageIO.write(image,"jpeg",outputStream);
            outputStream.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (outputStream != null)
            try{
                outputStream.close();
            }catch (IOException e){
                e.printStackTrace();
            }

        }

    }
}
